import json
import re

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.carts.utiles import merge_cart_cookie_to_redis
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import Users
from django_dome_meiduo import settings


class QQAuthURLView(View):
    '''
    向前端发送qq登陆页面链接
    '''

    def get(self, request):
        # next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next = request.GET.get('next')
        # 获取QQ登录页面网址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()

        return JsonResponse({'code': 0,
                             'errmsg': 'OK',
                             'login_url': login_url})


class QQAuthUserView(View):

    def get(self, requests):
        # 获取code
        # 通
        code = requests.GET.get("code")

        # 生成工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 获取 token
            qqtoken = oauth.get_access_token(code)

            # 获取 openid
            openid = oauth.get_open_id(qqtoken)

            print(openid)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": '获取用户信息失败'})

        # 判断有没有绑定
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except Exception  as e:
            print("没有绑定去绑定页面", e)

            # 加密
            openid = generate_access_token(openid)

            return JsonResponse({"code": 300, "errmsg": "快去绑定", "access_token": openid})

        else:
            # 没有报错 说明绑定了 直接登陆

            login(requests, qquser.user)

            # 设置cookei
            response = JsonResponse({"code": 0, "errmsg": "ok"})

            response.set_cookie("username", qquser.user.username)

            response = merge_cart_cookie_to_redis(requests, qquser.user, response)

            return response

    def post(self, request):

        data_dict = request.body.decode("utf-8")

        password = data_dict.get("password")
        mobile = data_dict.get("mobile")
        sms_code = data_dict.get("sms_code")
        openid = data_dict.get("access_token")

        # 验证数据
        if not all([password, mobile, sms_code, openid]):
            return JsonResponse({"code": 400, "errmsg": "信息不全"})

        # 验证短信验证码
        redis_cli = get_redis_connection("code")

        # 判断是否频繁发送
        sms_flg = redis_cli.get("sms_rtime_%s" % mobile)

        if not sms_flg is None:
            return JsonResponse({"code": 400, "errmsg": "不要频繁发送 。。。。。 are you ok？？"})

        redis_sms = redis_cli.get("sms_%s" % mobile)

        # 验证短信验证码
        if not (redis_sms and redis_sms.decoed() == sms_code):
            return JsonResponse({"code": 400, "errmsg": "手机验证码错误"})

        # 判断手机号有没有注册
        try:
            user = Users.objects.get(mobile=mobile)
        except Exception as e:
            # 如果没有注册  注册然后绑定
            new_user = Users()
            new_user.username = mobile
            new_user.mobile = mobile
            new_user.set_password(password)
            new_user.save()

            # 绑定

            login(request, new_user)

            response = JsonResponse({"code": 0, "errmsg": 'ok'})

            response.set_cookie("username", new_user.username)

            return response
        else:
            # 注册了就绑定 然后登陆

            # 验证密码是否正确
            ret = user.check_password(password)
            if not ret:
                return JsonResponse({"code": 400, "errmsg": "密码错误"})

            # 绑定
            new_qq = OAuthQQUser()
            new_qq.user = user
            new_qq.openid = check_access_token(openid)

            login(request, user)

            response = JsonResponse({"code": 0, "errmsg": 'ok'})

            response.set_cookie("username", user.username)

            response = merge_cart_cookie_to_redis(request, user, response)

            return response
